//
//  MainViewController.m
//  EZ Tracker
//
//  Created by FENGYL on 2016/11/1.
//  Copyright © 2016年 FENGYL. All rights reserved.
//

#import "MainViewController.h"
#import "LeftMenuTableViewController.h"
#import "UIView+XL.h"
#import "CoverView.h"
#import "DeviceCollectionViewCell.h"
#import "UserModel.h"
#import "AccountLogin.h"
#import "NetworkCommand.h"
#import "WGS84TOGCJ02.h"
#import "KCAnnotation.h"
#import "UIView+XL.h"
#import "PullUpDeviceTableView.h"
#import "PullUpDeviceTableViewCell.h"
#import "NetworkSocket.h"

#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
#import <AFNetworking.h>
#import <SVProgressHUD.h>

@interface MainViewController ()<MKMapViewDelegate,UICollectionViewDataSource,UITableViewDelegate,UITableViewDataSource>

@property (strong , nonatomic) IBOutlet UIScreenEdgePanGestureRecognizer *openMenuPan;
@property (strong , nonatomic) LeftMenuTableViewController * leftMenuTableViewController;
@property (weak, nonatomic) IBOutlet CoverView *coverView;
@property (strong , nonatomic) CLLocationManager * locationManager;
@property (strong , nonatomic) MKMapView *mapView;
@property (weak, nonatomic) IBOutlet UIView *topButtonView;
@property (weak, nonatomic) IBOutlet UIButton *satelliteButton;
@property (weak, nonatomic) IBOutlet UIButton *fullScreenButton;
@property (weak, nonatomic) IBOutlet UIView *bottomButtonView;
@property (weak, nonatomic) IBOutlet UIButton *plusButton;
@property (weak, nonatomic) IBOutlet UIButton *subButton;
@property (weak, nonatomic) IBOutlet UICollectionView *deviceCollectionView;

@property (strong , nonatomic) NSMutableArray * collectionDataArray;
@property (strong , nonatomic) AccountLogin * accountLogin;

@property (strong , nonatomic) UserModel * userModel;
@property (strong, nonatomic) NSMutableArray *activityIndicatorViewAnimationArray;
@property (strong, nonatomic) PullUpDeviceTableView *pullUpDeviceTableView;
@property (strong, nonatomic) UIView * windowCoverView;

@property (strong, nonatomic) NSTimer *refreshTimer;

@end

@implementation MainViewController

-(UserModel *)userModel{
    
    if (!_userModel) {
        _userModel = [[UserModel alloc]init];
    }
    return _userModel;
    
}

-(AccountLogin *)accountLogin{
    
    if (!_accountLogin) {
        
        _accountLogin = [AccountLogin accountLogin];
        
    }
    
    return _accountLogin;
    
}

-(NSMutableArray *)collectionDataArray{
    
    if (!_collectionDataArray) {
        _collectionDataArray = [NSMutableArray arrayWithCapacity:0];
    }
    
    return _collectionDataArray;
}

-(LeftMenuTableViewController *)leftMenuTableViewController{
    
    if (!_leftMenuTableViewController) {
        
        for (id controller  in self.childViewControllers) {
            
            if ([controller isKindOfClass:[LeftMenuTableViewController class]]) {
                
                _leftMenuTableViewController = controller;
                
            }
            
        }
        
    }
    
    return _leftMenuTableViewController;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.openMenuPan.edges = UIRectEdgeLeft;
    [self.openMenuPan addTarget:self action:@selector(panGesture:)];
    
    
    
    __block MainViewController * safeSelf = self;
    
    self.leftMenuTableViewController.changeCoverViewAlpha = ^{
    
        [safeSelf changeCoverViewAlpha];
    
    };
    
    
    self.coverView.hiddenLeftMenu = ^{
        
        [self touchMenuButton:nil];
        
    };
    
    
    [self setViewShadow:self.topButtonView];
    
    [self setViewShadow:self.bottomButtonView];
    
    [self locationEnable];
    
    [self setMap];
    
//    [self setPullUpDeviceTableView];
    
    self.satelliteButton.selected = NO;
    self.fullScreenButton.selected = NO;
    
    self.userModel.reLogin = NO;
    
    if (self.presentingViewController) {
        
        [self getAccountAttribute];
        
    }else{
        
//        NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
//        
//        
//        
//        [NetworkCommand userLoginUserName:[userDefaults valueForKey:UD_USERNAME] password:[userDefaults valueForKey:UD_PASSWORD] success:^{
//            
//             [self getAccountAttribute];
//            
//        } failure:^{
//            
//        }];
        
        [self.accountLogin accessToken:^{
            
           [self getAccountAttribute];
            
        }];
        
    }
    
    
    
    //刷新登录信息
//    self.refreshTimer = [NSTimer scheduledTimerWithTimeInterval:(15 * 60) repeats:YES block:^(NSTimer * _Nonnull timer) {
//        
//        NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
//        
//        NSString * password = [userDefaults objectForKey:UD_PASSWORD];
//        
//        NSString * username = [userDefaults objectForKey:UD_USERNAME];
//       
//        [NetworkCommand userLoginUserName:username password:password success:^{
//            
//            
//            
//        } failure:^{
//            
//            [NetworkCommand userLoginUserName:username password:password success:nil failure:nil];
//            
//        }];
//        
//    }];
    
    self.refreshTimer = [NSTimer scheduledTimerWithTimeInterval:(15 * 60) target:self selector:@selector(refreshTimerUpdateInfo) userInfo:nil repeats:YES];
    

    
}

#pragma mark 定期刷新登录信息
-(void)refreshTimerUpdateInfo{
    
    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
    
    NSString * password = [userDefaults objectForKey:UD_PASSWORD];
    
    NSString * username = [userDefaults objectForKey:UD_USERNAME];
    
    [NetworkCommand userLoginUserName:username password:password success:^{
        
        
        
    } failure:^{
        
        [NetworkCommand userLoginUserName:username password:password success:nil failure:nil];
        
    }];
    
    
}

#pragma mark 初始化上拉tableview
-(void)setPullUpDeviceTableView{
    
//    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    
    self.pullUpDeviceTableView = [[PullUpDeviceTableView alloc]initWithDelegate:self dataSource:self];
    
    self.windowCoverView = [[UIView alloc]initWithFrame:CGRectMake(0, [[UIApplication sharedApplication] statusBarFrame].size.height, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - [UIApplication sharedApplication].statusBarFrame.size.height)];
    
    [self.windowCoverView setBackgroundColor:[UIColor blackColor]];
    
    __block MainViewController *safeSelf = self;
    
    self.pullUpDeviceTableView.pullUpDeviceTableViewChangeCoverViewAlpha = ^(CGFloat pullUpMenuViewY){
        
        safeSelf.windowCoverView.alpha = ([UIScreen mainScreen].bounds.size.height - pullUpMenuViewY - 110) / ([UIScreen mainScreen].bounds.size.height - [UIApplication sharedApplication].statusBarFrame.size.height -110) / 2;
        
    };
    
    self.windowCoverView.alpha = 0;
    
    
    //改成添加在view上,不加在window上
    [self.view addSubview:self.windowCoverView];
    
    [self.view addSubview:self.pullUpDeviceTableView];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
    [self.refreshTimer invalidate];
    
}


#pragma mark 按钮阴影效果
-(void)setViewShadow:(UIView *)sender{
    
    sender.layer.shadowColor = [UIColor blackColor].CGColor;
    
    sender.layer.shadowOffset = CGSizeMake(2, 2);
    
    sender.layer.shadowOpacity = 0.4;
    
    sender.layer.shadowRadius = 4;
    
}

-(void)viewWillAppear:(BOOL)animated{
    
//    [self setPullUpDeviceTableView];
    
}

-(void)viewWillDisappear:(BOOL)animated{
    
    [self.windowCoverView removeFromSuperview];
    [self.pullUpDeviceTableView removeFromSuperview];
    
    
    //取消全屏
    self.fullScreenButton.selected = NO;
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    
}

-(void)viewDidAppear:(BOOL)animated{
    
//    [self setPullUpDeviceTableView];
    
    if (self.userModel.reLogin) {
        
        [self getAccountAttribute];
        
    }
    
}

-(void)viewDidDisappear:(BOOL)animated{
    
    if (self.leftMenuTableViewController.isOpen) {
        
        [self touchMenuButton:nil];
        
    }
    
}

#pragma mark 初始化地图

-(void)setMap{
    
    self.mapView = [[MKMapView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    
    [self.view addSubview:self.mapView];
    
    [self.view sendSubviewToBack:self.mapView];
    
    self.mapView.delegate = self;
    
    self.mapView.userTrackingMode = MKUserTrackingModeFollow;
    
    self.mapView.mapType = MKMapTypeStandard;
    
    NSLog(@"MapCamera %@",self.mapView.camera);
    
    
}


#pragma mark 手势打开菜单
-(void)panGesture:(UIPanGestureRecognizer *)gesture{
    
    
    
    CGPoint translation = [gesture translationInView:gesture.view];
    NSLog(@"%@",[NSString stringWithFormat:@"(%0.0f, %0.0f)", translation.x, translation.y]);
    
    if (!self.leftMenuTableViewController.isOpen) {
        
        if (gesture.state == UIGestureRecognizerStateEnded) {
            
            if (translation.x > self.leftMenuTableViewController.tableView.width/3 * 2) {
                
                [UIView animateWithDuration:0.3 animations:^{
                    
                    self.leftMenuTableViewController.tableView.superview.transform = CGAffineTransformIdentity;
                    
                    
                    
                    [self changeCoverViewAlpha];
                    
                }];
                
                self.leftMenuTableViewController.isOpen = YES;
                
            }else{
                
                [UIView animateWithDuration:0.3 animations:^{
                    
                    self.leftMenuTableViewController.tableView.superview.transform = CGAffineTransformMakeTranslation(-self.leftMenuTableViewController.tableView.width, 0);
                    
                    
                    
                    [self changeCoverViewAlpha];
                    
                }];
                
                self.leftMenuTableViewController.isOpen = NO;
                
            }
            
        }else{
            
            //滑动
            if (translation.x < self.leftMenuTableViewController.tableView.width) {
                
                CGFloat x = translation.x - self.leftMenuTableViewController.tableView.width;
                
                if (translation.x > self.leftMenuTableViewController.tableView.width) {
                    
                    self.leftMenuTableViewController.tableView.superview.transform = CGAffineTransformIdentity;
                    
                
                    
                }else{
                    
                    self.leftMenuTableViewController.tableView.superview.transform = CGAffineTransformMakeTranslation(x, 0);
                    
                    
                }
                
                [self changeCoverViewAlpha];
                
            }
            
            
            
            
        }
        
    }
    
    
    
    
    
}

#pragma mark 遮盖层的透明值
-(void)changeCoverViewAlpha{
    
    //遮盖层的透明值
    self.coverView.alpha = (self.leftMenuTableViewController.tableView.superview.transform.tx + self.leftMenuTableViewController.tableView.width)/(self.leftMenuTableViewController.tableView.width * 2);
    
    
    //上拉菜单隐藏(加在window上,不调整会盖在左拉菜单上)
    if (self.coverView.alpha == 0) {
        
        [UIView animateWithDuration:0.3 animations:^{
            
            self.pullUpDeviceTableView.x = 0;
            
        }];
        
        
        
    }else{
        
        [UIView animateWithDuration:0.3 animations:^{
            
            self.pullUpDeviceTableView.x = [UIScreen mainScreen].bounds.size.width;
            
        }];
        
        
        
    }
    
}


#pragma mark 打开/关闭菜单
- (IBAction)touchMenuButton:(id)sender {
    
    [self.leftMenuTableViewController changeViewTransform];
    
    //遮盖层的透明值
    if (self.leftMenuTableViewController.isOpen) {
        
        [UIView animateWithDuration:0.3 animations:^{
            
            self.coverView.alpha = 0.5;
            
            //上拉菜单隐藏(加在window上,不调整会盖在左拉菜单上)
            self.pullUpDeviceTableView.x = [UIScreen mainScreen].bounds.size.width;
            
        }];
        
    }else{
        
        [UIView animateWithDuration:0.3 animations:^{
            
            self.coverView.alpha = 0;
            
            //上拉菜单隐藏(加在window上,不调整会盖在左拉菜单上)
            self.pullUpDeviceTableView.x = 0;
            
        }];
        
    }
    
}

#pragma mark 判断是否有权限
-(void)locationEnable{
    
    self.locationManager = [[CLLocationManager alloc] init];
    
    //是否具有定位权限
    int status=[CLLocationManager authorizationStatus];
    
    //请求权限
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8)
    {
        //由于IOS8中定位的授权机制改变 需要进行手动授权
        
        //获取授权认证
        [self.locationManager requestAlwaysAuthorization];
    }
    
    if (status < 3 || ![CLLocationManager locationServicesEnabled]){
        
        UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"The user is not allowed to turn on the location service" message:@"Please turn on location service" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction * confirmAction = [UIAlertAction actionWithTitle:@"Setting" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if ([[UIApplication sharedApplication] canOpenURL:url])
            {
                [[UIApplication sharedApplication] openURL:url];
                
            }
            
        }];
        
        UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alertController addAction:confirmAction];
        [alertController addAction:cancelAction];
        
        [self presentViewController:alertController animated:YES completion:nil];
        
    }else{
        
       
        
    }
    
}

#pragma mark 添加大头针
-(void)addAnnotationForResponseObject:(NSArray *)responseObject serialNumber:(NSString *)serialNumber deviceName:(NSString *)deviceName{
    
    NSDictionary *dict = responseObject[0];
    
    NSNumber *latitude = [dict valueForKey:NC_LAT];
    
    NSNumber *longitude = [dict valueForKey:NC_LNG];
    
    
    
    
    if ([latitude floatValue] != 0 && [longitude floatValue] != 0 && [self.userModel.selectedDeviceSerialNumberArray containsObject:serialNumber]) {
        
        
        //获取准确坐标
        CLLocationCoordinate2D location = CLLocationCoordinate2DMake([latitude floatValue], [longitude floatValue]);
        
        
        CLLocationCoordinate2D fixLocation;
        
        if (![WGS84TOGCJ02 isLocationOutOfChina:location]) {
            
            fixLocation = [WGS84TOGCJ02 transformFromWGSToGCJ2:location];
            
        }else{
            
            fixLocation = location;
            
        }
        
        
        
        KCAnnotation *annotation = [[KCAnnotation alloc]init];
        annotation.coordinate = fixLocation;
        
        //合成图片
        NSInteger powerValue = [[dict valueForKey:NC_POWER_VALUE] integerValue];

        UIImage *powerImage;
        
        if (powerValue >= 70) {
            
            powerImage = [UIImage imageNamed:@"ic_power_full"];
            
        }else if (powerValue < 70 && powerValue >= 20){
            
            powerImage = [UIImage imageNamed:@"ic_power_medium"];
            
        }else{
            
            powerImage = [UIImage imageNamed:@"ic_power_low"];
            
        }
        
        UIImage *iconImage = [self.userModel.deviceIconDictionary valueForKey:serialNumber];
        
        if (!iconImage) {
            
            iconImage = [UIImage imageNamed:@"ic_tracker_useractivity_yuan_2"];
            
        }
        
        annotation.image = [self addImage:[UIImage imageNamed:@"ic_track_marker_boy_2"] toImage:iconImage powerImage:powerImage powerValue:powerValue deviceName:deviceName];
        
        
        
        [_mapView addAnnotation:annotation];
        
        [self.userModel.mainViewControllerAnnotationDictionary setValue:annotation forKey:serialNumber];
        
        NSLog(@"add annotation %@",serialNumber);
        
        NSLog(@"mainViewControllerAnnotationDictionary %@",self.userModel.mainViewControllerAnnotationDictionary);
        
        
        
        double eyeAltitude;
        
        if (_mapView.camera.altitude > STATIC_ALTITUDE) {
            
            eyeAltitude = STATIC_ALTITUDE;
            
        }else{
            
            eyeAltitude = _mapView.camera.altitude;
            
        }
        
        //移动到大头针位置
        MKMapCamera *mkMapCamera = [MKMapCamera cameraLookingAtCenterCoordinate:fixLocation fromEyeCoordinate:fixLocation eyeAltitude:eyeAltitude];
        
        if (fabs(fixLocation.latitude) <= 90 && fabs(fixLocation.longitude) < 180 ) {
            [_mapView setCamera:mkMapCamera animated:YES];
        }
//        [_mapView setCamera:mkMapCamera animated:YES];
        
        NSLog(@"altitude %f",_mapView.camera.altitude);
        
    }else{
        
        if (![self.userModel.selectedDeviceSerialNumberArray containsObject:serialNumber]) {
            
            return;
            
        }
        
        [SVProgressHUD showErrorWithStatus:@"No Data."];
        
        [SVProgressHUD dismissWithDelay:1];
        
        [self.userModel.selectedDeviceSerialNumberArray removeObject:serialNumber];
        
        [_deviceCollectionView reloadData];
        
        
    }
    
    

}

#pragma mark 合成图片
- (UIImage *)addImage:(UIImage *)image1 toImage:(UIImage *)image2 powerImage:(UIImage *)powerImage powerValue:(NSInteger)powerValue deviceName:(NSString *)deviceName{
    
//    CGFloat circleWidth = powerImage.size.width + 15;
    
    NSDictionary *deviceNameAttributes = @{NSFontAttributeName:[UIFont systemFontOfSize:10],NSForegroundColorAttributeName:[UIColor whiteColor]};
    
    CGRect deviceNameSizeToFit = [deviceName boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, 10) options:NSStringDrawingUsesDeviceMetrics attributes:deviceNameAttributes context:nil];
    
    NSLog(@"deviceNameSizeToFit %f",deviceNameSizeToFit.size.width);
    
    
    NSLog(@"image1 %f",image1.size.width);
    
    
    //info图片
    
    
    
    
    //电量string
    NSString *powerString = [NSString stringWithFormat:@"%ld%%",(long)powerValue];
    
    NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:10],NSForegroundColorAttributeName:[UIColor whiteColor]};
    
    CGRect sizeToFit = [powerString boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, 10) options:NSStringDrawingUsesDeviceMetrics attributes:attributes context:nil];
    

    
    
    CGFloat infoHeight = deviceNameSizeToFit.size.height + powerImage.size.height + 15;
    
    CGFloat infoWidth;
    
    CGFloat margin;
    
    CGFloat deviceNameX;
    
    if (powerImage.size.width + sizeToFit.size.width + 5 > deviceNameSizeToFit.size.width) {
        
        infoWidth = powerImage.size.width + sizeToFit.size.width + 25;
        
        margin = (infoWidth - powerImage.size.width - sizeToFit.size.width)/2;
        
        deviceNameX = (infoWidth - deviceNameSizeToFit.size.width) / 2 ;
        
    }else{
        
        infoWidth = deviceNameSizeToFit.size.width + 20;
        
        margin = (infoWidth - powerImage.size.width - sizeToFit.size.width)/2 + 5;
        
        deviceNameX = 10;
        
    }
    
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(infoWidth, infoHeight), NO, 0.0);
    
    
    
    
    
    
    UIImage *infoImage = [UIImage imageNamed:@"power&username2"];

    [infoImage drawInRect:CGRectMake(0, 0, infoWidth, infoHeight)];
    
    [deviceName drawAtPoint:CGPointMake(deviceNameX, 5) withAttributes:deviceNameAttributes];
    
    
    
    
    [powerString drawAtPoint:CGPointMake(margin + powerImage.size.width + 5,deviceNameSizeToFit.size.height + 10) withAttributes:attributes];
    
    [powerImage drawAtPoint:CGPointMake(margin,deviceNameSizeToFit.size.height + 10)];
    
    
    
    
    UIImage *circleImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    
    CGFloat infoImageMarginHeight = circleImage.size.height / 2;
    
    //大头针
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(image1.size.width + circleImage.size.width, image1.size.height + infoImageMarginHeight), NO, 0.0);
    
    // Draw image1
    [image1 drawInRect:CGRectMake(0, infoImageMarginHeight, image1.size.width, image1.size.height)];
    
    // Draw image2
    [image2 drawInRect:CGRectMake(2, infoImageMarginHeight + 2, image1.size.width - 4, image1.size.width - 4)];
    
    [circleImage drawInRect:CGRectMake(image1.size.width, 0, circleImage.size.width, circleImage.size.height)];
    
    UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return resultingImage;
}

#pragma mark 移除大头针
-(void)removeAnnotationFromMapViewForSerialNumber:(NSString *)serialNumber;
{
    
    KCAnnotation * annotation = [self.userModel.mainViewControllerAnnotationDictionary valueForKey:serialNumber];
    
    [_mapView removeAnnotation:annotation];
    
    NSLog(@"mainViewControllerAnnotationDictionary %@",self.userModel.mainViewControllerAnnotationDictionary);
    
    [self.userModel.mainViewControllerAnnotationDictionary removeObjectForKey:serialNumber];
    
    NSLog(@"mainViewControllerAnnotationDictionary %@",self.userModel.mainViewControllerAnnotationDictionary);
}

#pragma mark - 地图控件代理方法
#pragma mark 显示大头针时调用，注意方法中的annotation参数是即将显示的大头针对象
-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{
    //由于当前位置的标注也是一个大头针，所以此时需要判断，此代理方法返回nil使用默认大头针视图
    if ([annotation isKindOfClass:[KCAnnotation class]]) {
        static NSString *key1=@"AnnotationKey1";
        MKAnnotationView *annotationView=[_mapView dequeueReusableAnnotationViewWithIdentifier:key1];
        
        //算中心点
        CGFloat pointCenterPercent = 30.0 / ((KCAnnotation *)annotation).image.size.width;
        
        NSLog(@"pointCenterPercent %f",pointCenterPercent);
        
        //如果缓存池中不存在则新建
        if (!annotationView) {
            annotationView=[[MKAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:key1];
            annotationView.canShowCallout=true;//允许交互点击
            annotationView.calloutOffset=CGPointMake(0, 0);//定义详情视图偏移量
            annotationView.layer.anchorPoint = CGPointMake(pointCenterPercent, 1);
            annotationView.leftCalloutAccessoryView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"icon_classify_cafe.png"]];//定义详情左侧视图
        }
        
        //修改大头针视图
        //重新设置此类大头针视图的大头针模型(因为有可能是从缓存池中取出来的，位置是放到缓存池时的位置)
        annotationView.annotation=annotation;
        annotationView.image=((KCAnnotation *)annotation).image;//设置大头针视图的图片
        
        
        return annotationView;
    }else {
        return nil;
    }
}

#pragma mark 拖动时调用 (remove 再重新添加地图 减少内存使用 5c是cpu爆炸所以没卵用 还是卡)
-(void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated{
    
//    [self.mapView removeFromSuperview];
//    
//    [self.view addSubview:self.mapView];
//    
//    [self.view sendSubviewToBack:self.mapView];
    
}


#pragma mark 卫星地图按钮点击事件
- (IBAction)changeMapType:(id)sender {
    
    if (self.satelliteButton.selected) {
        
        self.mapView.mapType = MKMapTypeStandard;
        
    }else{
        
        self.mapView.mapType = MKMapTypeSatellite;
        
    }
    
    
    self.satelliteButton.selected = !self.satelliteButton.selected;
    
}

#pragma mark 全屏按钮点击事件
- (IBAction)mapFullScreen:(id)sender {
    
    if (self.fullScreenButton.selected) {
        
        [self.navigationController setNavigationBarHidden:NO animated:YES];
        
        
    }else{
        
        
        [self.navigationController setNavigationBarHidden:YES animated:YES];
            
        
    }
    
    
    self.fullScreenButton.selected = !self.fullScreenButton.selected;
    
}

#pragma mark collectionView
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.collectionDataArray.count;
    
}

// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    DeviceCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"DeviceCell" forIndexPath:indexPath];
    
    if (self.collectionDataArray.count > 0) {
        
        NSDictionary * dict = self.collectionDataArray[indexPath.row];
        
        //设置deviceName
        
        NSString *deviceName;
        
        if ([self.userModel.changeDeviceNameDictionary valueForKey:[dict valueForKey:NC_SERIAL_NUMBER]]) {
            
            deviceName = [self.userModel.changeDeviceNameDictionary valueForKey:[dict valueForKey:NC_SERIAL_NUMBER]];
            
        }else{
            
            deviceName = [dict valueForKey:NC_DISPLAY_NAME];
            
        }
        
        [cell setDeviceName:deviceName serialNumber:[dict valueForKey:NC_SERIAL_NUMBER]];
        
        UIImage *image = [self.userModel.deviceIconDictionary valueForKey:[dict valueForKey:NC_SERIAL_NUMBER]];
        
        [cell setUpIconImage:image];
        
    }
    
    [cell activityIndicatorViewStartAnimating];
    
    
    
    
    
    return cell;
}

#pragma mark tableView
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.collectionDataArray.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSDictionary *dict = self.collectionDataArray[indexPath.row];
    
    PullUpDeviceTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PullUpDeviceTableViewCell"];
    
    if (cell == NULL) {
        
        cell = [[PullUpDeviceTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"PullUpDeviceTableViewCell"];
        
    }
    
    NSString *serialNumber = [dict valueForKey:NC_SERIAL_NUMBER];
    
    UIImage *image = [self.userModel.deviceIconDictionary valueForKey:serialNumber];
    
    if (!image) {
        
        image = [UIImage imageNamed:@"ic_tracker_useractivity_yuan_2"];
        
    }
    
    [cell setUpCellForDeviceIcon:image serialNumber: serialNumber deviceName:[dict valueForKey:NC_DISPLAY_NAME] isSelect:![serialNumber isEqualToString:self.userModel.selectedDeviceSerialNumber]];
    
    return cell;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 60;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    PullUpDeviceTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    self.userModel.selectedDeviceSerialNumber = [cell getSerialNumberString];
    
    [self.pullUpDeviceTableView reloadData];
    
}

#pragma mark 刷新
-(void)reloadTableViewOrCollectionView{
    
    [self.deviceCollectionView reloadData];
    
}

#pragma mark 获取账户信息
-(void)getAccountAttribute{
    
//    MBProgressHUD * hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//    
//    hud.mode = MBProgressHUDModeIndeterminate;
//    
//    [hud.label setText:@"Waitting..."];
//    
//    hud.removeFromSuperViewOnHide = YES;
    
    [SVProgressHUD showWithStatus:@"Waitting..."];
    
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
    
    UserModel * userModel = [[UserModel alloc]init];
    
    userModel.reLogin = NO;
    
    if (!userModel.userID && !userModel.tokenPass && !userModel.clientType) {
        
        return;
        
    }
    
    NSMutableDictionary * parameters = [ NSMutableDictionary dictionary];
    
    parameters[@"Id"] = userModel.userID;
    parameters[@"ClientType"] = userModel.clientType;
    parameters[@"TokenPass"] = userModel.tokenPass;
    
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    
    NSString * postUrl = [NSString stringWithFormat:@"%@%@",SERVICE_URL,GET_DEVICES_BY_ACCOUNT];
    
    [manager POST:postUrl parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //collectionDataArry初始化
        self.collectionDataArray = nil;
        
        [self.collectionDataArray addObjectsFromArray:responseObject];
        
        userModel.deviceByAccountArray = self.collectionDataArray;
        
        NSDictionary * dict;
        
        if (self.collectionDataArray.count > 0) {
            
            dict = self.collectionDataArray[0];
            
        }
        
        userModel.selectedDeviceSerialNumber = [dict valueForKey:NC_SERIAL_NUMBER];
        
        [self.deviceCollectionView reloadData];
        
        [self.pullUpDeviceTableView reloadData];
        
        NSLog(@"%@",responseObject);
        
        
//        NSDictionary * dict = self.collectionDataArray[0];
        
        userModel.currentDeviceName = [dict valueForKey:NC_DISPLAY_NAME];
        
        userModel.currentDeviceSerialNumber = [dict valueForKey:NC_SERIAL_NUMBER];
        
//        hud.mode = MBProgressHUDModeCustomView;
//        
//        [hud.label setText:@"Connection Success."];
//        
//        [hud hideAnimated:YES afterDelay:0.5];
        
        [SVProgressHUD showSuccessWithStatus:@"Connection Success."];
        
        [SVProgressHUD dismissWithDelay:1];
        
//        [NetworkCommand getDeviceAttrsOfSuccess:^{
//            
//            [self.deviceCollectionView reloadData];
//            
//        } failure:^{
//            
//            
//            
//        }];
        
//        NetworkSocket *networkSocket = [[NetworkSocket alloc]init];
//        
//        [networkSocket socketConnected];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
//        [hud.label setText:@"Connection failed."];
//        
//        hud.mode = MBProgressHUDModeText;
//        
//        hud.removeFromSuperViewOnHide = YES;
//        
//        [hud hideAnimated:YES afterDelay:0.5];
        
        [SVProgressHUD showErrorWithStatus:@"Connection failed."];
        
        [SVProgressHUD dismissWithDelay:1];
        
        
        NSLog(@"%@",error);
        
        
        
    }];
    
}

#pragma mark 列表多选调用
-(void)deviceSelectFromMainDeviceTableViewForSelectedArray:(NSMutableArray *)selectedArray{
    
    //缺少的serialnumberArray
    NSMutableArray *lessArray = [NSMutableArray array];
    
    if (self.userModel.selectedDeviceSerialNumberArray.count > 0) {
        
        for (NSString *selectSerialNumber in self.userModel.selectedDeviceSerialNumberArray) {
            
            if (![selectedArray containsObject:selectSerialNumber]) {
                
                [lessArray addObject:selectSerialNumber];
                
                
            }
            
        }
        
    }
    
    //取消选中
    if (lessArray.count > 0) {
        
        for (NSString *selectSerialNumber in lessArray) {
            
            for (DeviceCollectionViewCell *cell in self.deviceCollectionView.visibleCells) {
                
                NSString *serialNumber = [cell getSerialNumberString];
                
                if ([serialNumber isEqualToString:selectSerialNumber]) {
                    
                    [cell selectDevice:nil];
                    
                }
                
                
            }
            
        }
        
        
        
    }
    
    
    
    if (selectedArray.count > 0) {
        
        for (NSString *selectSerialNumber in selectedArray) {
            
            if (![self.userModel.selectedDeviceSerialNumberArray containsObject:selectSerialNumber]) {
                
                for (DeviceCollectionViewCell *cell in self.deviceCollectionView.visibleCells) {
                    
                    NSString *serialNumber = [cell getSerialNumberString];
                    
                    if ([serialNumber isEqualToString:selectSerialNumber]) {
                        
                        [cell selectDevice:nil];
                        
                    }
                    
                    
                }
                
            }
            
        }
        
    }
    
    
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
